package com.crazy.practice.boot.even;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Service;

import java.util.Enumeration;
import java.util.Properties;

/**
 * @author panyonghui
 * @describe 配置变更处理
 * @date 2023/4/13 16:53
 */
@Slf4j
@Service
public class PropertiesChangeHandle {

    /**
     * 配置项
     */
    @Autowired
    private ConfigurableEnvironment configurableEnvironment;

    /**
     * 监听器事件发布器
     */
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 配置变更
     * @param properties
     * @return void
     * @modify
     */
    public void changeProperties(Properties properties){
        if (properties == null){
            return;
        }
        log.info("通过实现@EventListener注解监听配置变更");
        Properties oldProperties = new Properties();
        Properties newProperties = new Properties();
        Enumeration enumeration = properties.propertyNames();
        while(enumeration.hasMoreElements()){
            String keyName = (String) enumeration.nextElement();
            // 旧参数
            Object oldValue = configurableEnvironment.getProperty(keyName);
            // 新参数
            Object newValue = properties.getProperty(keyName);
            if (oldValue != null){
                oldProperties.put(keyName, oldValue);
            }
            if (newValue != null && !newValue.equals(oldValue)){
                newProperties.put(keyName, newValue);
            }
        }
        PropertiesChangeEven propertiesChangeEven = new PropertiesChangeEven(properties);
        propertiesChangeEven.setOldProperties(oldProperties);
        propertiesChangeEven.setNewProperties(newProperties);
        // 发版配置变更事件
        applicationEventPublisher.publishEvent(propertiesChangeEven);
    }
}
